import { deleteUserRoleApi, getUserRoleListApi } from '@/services/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { Button, Popconfirm, message } from 'antd';
import { isEqual } from 'lodash';
import React, { useRef, useState } from 'react';
import CreateBindRuleDrawer from '../Drawer/CreateBindRuleDrawer';
import CreatePermission from '../Drawer/CreatePermission';

const UserRole: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const [createRuleDrawerParams, setCreateRuleDrawerParams] = useState({
    open: false,
    info: {},
    type: 'add',
  });

  // 配置权限弹窗
  const [createPermission, setCreatePermission] = useState({
    open: false,
    info: {},
  });

  const {
    user_role_config_permissions_permissions_add,
    user_role_config_permissions_permissions_edit,
    user_role_config_permissions_permissions_delete,
  } = useAccess() as any;

  const columns: any = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '角色名称',
      dataIndex: 'title',
      hideInSearch: true,
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 158,
      render: (text: any, record: any) => [
        user_role_config_permissions_permissions_edit && (
          <a
            key="pei"
            onClick={() => {
              setCreatePermission({
                open: true,
                info: record,
              });
            }}
          >
            配置权限
          </a>
        ),
        user_role_config_permissions_permissions_edit && (
          <a
            key="editable"
            onClick={() => {
              setCreateRuleDrawerParams({
                open: true,
                info: record,
                type: 'edit',
              });
            }}
          >
            编辑
          </a>
        ),
        user_role_config_permissions_permissions_delete && (
          <Popconfirm
            key="bofan"
            title={`确定删除该角色- ${record?.title}`}
            onConfirm={async () => {
              try {
                await deleteUserRoleApi(record?.id);
                message.success('删除成功');
                actionRef.current?.reload();
              } catch (error) {}
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button className="_common_card_left_item_btn" type="link" danger>
              删除
            </Button>
          </Popconfirm>
        ),
      ],
    },
  ];

  return (
    <>
      <ProTable
        bordered
        columns={columns}
        actionRef={actionRef}
        cardBordered
        // scroll={{ x: 1200 }}
        request={async (_parame) => {
          const { pageSize, current, ...ret } = _parame;
          const { data } = await getUserRoleListApi({
            page: current,
            size: pageSize,
            ...ret,
          });
          return {
            data: data?.list ?? [],
            success: true,
            total: data?.count,
          };
        }}
        rowKey="id"
        search={false}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          defaultPageSize: 10,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          user_role_config_permissions_permissions_add && (
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                setCreateRuleDrawerParams({
                  open: true,
                  info: {},
                  type: 'add',
                });
              }}
              type="primary"
            >
              新增角色
            </Button>
          ),
        ]}
      />

      {createRuleDrawerParams.open && (
        <CreateBindRuleDrawer
          open={createRuleDrawerParams.open}
          info={createRuleDrawerParams.info}
          close={() => {
            setCreateRuleDrawerParams({
              open: false,
              info: '',
              type: 'add',
            });
          }}
          onFinish={() => {
            setCreateRuleDrawerParams({
              open: false,
              info: '',
              type: 'add',
            });
            actionRef.current?.reload();
          }}
          type={createRuleDrawerParams?.type}
        ></CreateBindRuleDrawer>
      )}
      {/* // 配置权限 */}
      {createPermission.open && (
        <CreatePermission
          open={createPermission.open}
          info={createPermission.info}
          close={() => {
            setCreatePermission({
              open: false,
              info: '',
            });
          }}
          onFinish={() => {
            setCreatePermission({
              open: false,
              info: '',
            });
            actionRef.current?.reload();
          }}
        />
      )}
    </>
  );
};
export default React.memo(UserRole, (prev, next) => isEqual(prev, next));
